import dayjs from 'dayjs'
import Schema from 'validate'
const formInfo = new Schema({
  houseId: {
    type: String,
    required: true,
    message: '请选择房屋'
  },
  visitDate: {
    type: String,
    required: true,
    message: '请选择时间'
  },
  name: {
    type: String,
    required: true,
    message: '请填写姓名'
  },
  gender: {
    type: Number,
    required: true,
    message: '请填写性别'
  },
  mobile: {
    type: String,
    required: true,
    match: /^1[3-9]\d{9}$/,
    message: '请填写手机号'
  }
})
Page({
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    // 可选房屋列表
    houseList: [],
    // 可选房屋名称
    houseInfo: '',
    // 可选房屋id
    houseId: '',
    // 当前时间
    currentDate: +dayjs(),
    // 最小时间
    minDate: +dayjs(),
    // 最大时间
    maxDate: +dayjs().add(3, 'day'),
    // 选择的时间
    visitDate: '',
    // 姓名
    name: '',
    // 性别
    gender: 1,
    // 手机号
    mobile: ''
  },
  onLoad () {
    this.getHouseLinst()
  },
  // 获取可选房屋
  async getHouseLinst () {
    const res = await wx.http({ url: '/house' })
    console.log(res)
    this.setData({ houseList: res.data })
  },
  // 获取选择的房屋名称和id
  onHouseSelect (e) {
    // console.log(e)
    const { name, id } = e.detail
    this.setData({
      houseInfo: name,
      houseId: id
    })
  },
  // 获取选择的时间
  onSelectData (e) {
    // console.log(e.detail)
    this.setData({
      currentDate: e.detail,
      visitDate: dayjs(e.detail).format('YYYY-MM-DD'),
      dateLayerVisible: false
    })
  },
  // 确认提交
  async goPassport () {
    const { houseId, visitDate, name, gender, mobile } = this.data
    const data = { houseId, visitDate, name, gender, mobile }

    const errors = formInfo.validate(data)
    if (errors.length) {
      return wx.utils.toast(errors[0].message)
    }
    await wx.http({ url: '/visitor', method: 'POST', data })
    wx.showToast({ title: '成功', icon: 'success' })
    setTimeout(() => {
      wx.navigateTo({
        url: '/visitor_pkg/pages/list/index'
      })
    }, 1500)
  },
  openHouseLayer () {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer () {
    this.setData({ houseLayerVisible: false })
  },
  openDateLayer () {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer () {
    this.setData({ dateLayerVisible: false })
  }
  // goPassport () {
  //   wx.reLaunch({
  //     url: '/visitor_pkg/pages/passport/index'
  //   })
  // }
})
